package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.SelectPage;
import com.itheima.pojo.User;
import com.itheima.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    //分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable int currentPage, @PathVariable int pageSize) throws IOException {

        IPage<User> page = new Page<>(currentPage, pageSize);
        userMapper.selectPage(page, null);
        //List<User> records = page.getRecords();
        //System.out.println(records);
        SelectPage selectPage = new SelectPage(page.getRecords(), page.getTotal());

        Result result = new Result();
        result.setCode(Code.GET_OK);
        result.setData(selectPage);
        result.setMsg("查询成功");

        return result;
    }

    /**
     * 保存用户
     *
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody User user) {
        int insert = userMapper.insert(user);

        return new Result(Code.SAVE_OK,null);
    }

    /**
     * 根据用户id查询用户
     *
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        int i = userMapper.deleteById(id);

        if (i == 1){
            return new Result(Code.DELETE_OK,null);
        }else {
            return new Result(Code.DELETE_ERR,null);
        }

    }

    /**
     * 更新用户
     *
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        int i = userMapper.updateById(user);
        if(i == 1){
            return new Result(Code.UPDATE_OK,null);
        }else {
            return new Result(Code.UPDATE_ERR,null);
        }
    }

}
